// pages/index/index.js
Page({
  data: {
    memorialList: [], 
  },
  
  onLoad() {
    this.loadMemorialList();
    
    // 注册事件监听器
    const app = getApp();
    app.eventBus.on('memorial-updated', this.loadMemorialList);
  },
  
  onUnload() {
    // 移除事件监听器
    const app = getApp();
    app.eventBus.off('memorial-updated', this.loadMemorialList);
  },
  
  loadMemorialList() {
    const list = wx.getStorageSync('memorialList') || [];
    const now = new Date().getTime();
    const updatedList = list.map(item => {
      const targetTime = new Date(item.date).getTime();
      const days = Math.abs(Math.ceil((targetTime - now) / (1000 * 3600 * 24)));
      return { ...item, days };
    });
    this.setData({ memorialList: updatedList });
  },
  
  goToAdd() {
    wx.navigateTo({ url: '/pages/add/add' });
  },
  
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({ url: `/pages/detail/detail?id=${id}` });
  },
  
  formatDate(dateStr) {
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`;
  }
});
